package com.lucas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lucas.mapper.TokenMapper;
import com.lucas.pojo.Lagou_token;
import com.lucas.service.TokenService;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @program: spring_cloud_lagou_homework
 * @author: lucasLu
 * extends ServiceImpl<TokenMapper,lagou_token>
 **/
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, Lagou_token> implements TokenService {
    @Override
    public String getEmailByToken(String token) {
        Lagou_token item = new Lagou_token();
        item.setToken(token);
        QueryWrapper<Lagou_token> queryWrapper = new QueryWrapper<>(item);
        Lagou_token lagou_token = baseMapper.selectOne(queryWrapper);
        if(lagou_token == null){
            return null;
        }
        return lagou_token.getEmail();

    }



    @Override
    public String getOrCreatToken(String mail) {
        Lagou_token item =new Lagou_token();
        item.setEmail(mail);
        QueryWrapper<Lagou_token> queryWrapper = new QueryWrapper<Lagou_token>();
        Lagou_token lagou_token = baseMapper.selectOne(queryWrapper);

        if(lagou_token !=  null){
            return  lagou_token.getToken();
        }

        //创建并入库
        String token = UUID.randomUUID().toString();
        lagou_token = new Lagou_token();
        lagou_token.setEmail(mail);
        lagou_token.setToken(token);
        int insert = baseMapper.insert(lagou_token);
        if(insert == 0){
            return null;
        }

        return token;
    }
}
